/*
 * Author: Roy Stegers & Gino Biervliet
 *
 * This function analyzes commands
 *
 */


#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/stat.h>
#include <semaphore.h>
#include "hfile.h"


//comandAna requires an int with the client fd, a string with the command and a clientInfo struct
int commandAna(int descClient, char cBuffer[CHUNKSIZE], clientInfo client[]  )
{
    int iCount, iCountArg = 0;//counters
    char cCommand[CHUNKSIZE], cRecvBuffer[CHUNKSIZE];//buffers
    char cArg[ARGSIZE];

    printf("begin command ana \n");//Debug
    
    //Substract the command part and put the value in cCommand
    for(iCount = 0;cBuffer[iCount] != ' '; iCount++)
    {
        cCommand[iCount] = cBuffer[iCount];
    }

    cCommand[iCount] = '\0';//set last char to eof

    iCount ++;  //Hop over space

    //Substract agrumand and put value in sArg, starting from the point that  icount left of.
    while((cBuffer[iCount]!= ' ') && (cBuffer[iCount]!= '\0'))
    {
        cArg[iCountArg] = cBuffer[iCount];
        ++iCount;
        iCountArg++;
    }

    iCountArg=0;    //Set iCountArg on zero so dat the next argument starts again with 0.
    printf("passed splitting of buffer\n");
    //Use strcmp to compare cCommand value with any known command


    //if quit .. then exit thread(future)
    if(strcmp(cCommand, "QUIT") == 0)
    {
        printf("Quit\n");
        bzero(cBuffer,CHUNKSIZE);
        bzero(cCommand,CHUNKSIZE);
        close(descClient);
        return 2;
    }

    //handle upload
    if(strcmp(cCommand, "UPLOAD")==0)
    {

        printf("Upload\n");     //Debug line
        bzero(cRecvBuffer, CHUNKSIZE);//empty variable to make sure no exess data is read.
        lseek(client[descClient].iMapFd, 0, SEEK_SET);//set offset of mmf to 0 (beginning of file)

        //write given msg to fsp, buffer form client with upload.
        if((write(client[descClient].iMapFd, cBuffer, strlen(cBuffer))) < 0)
        {
            perror("Write to mmf\n");
        }

        printf("Written ot mmap: %s\n", client[descClient].cMapFile);   //Debug line

        //unlock semfull, so that the FSP can read the command
        if(sem_post(client[descClient].semaphoreFull) < 0)
        {
            perror("sem_wait semaEmpty in download\n");
        }

        printf("Post semEmpty done\n");     //Debug line

        //wait for sem empty .. name is not correct in this case but well use it anyway because else we have to create another sem. We get a READY respose form FSP
        if(sem_wait(client[descClient].semaphoreEmpty) < 0)
        {
            perror("sem_wait semaEmpty in commandana download\n");  
        }
        printf("Wait semFull done\n");//Debug
        //if fsp sends ready .. send ready to client and start download else send error and abort

        printf("ARE YOU READY KIDS!?: %s\n", client[descClient].cMapFile);      //Debug line
        //check if MMF says READY
        if(strcmp(client[descClient].cMapFile, "READY") == 0)
        {
            //send
            if(send(descClient, client[descClient].cMapFile, strlen(client[descClient].cMapFile), 0) < 0)
            {
                perror("recv upload funct\n");
            }
                //Run upload
                upload(client[descClient].clientNo, client);
                printf("==============================Returned out upload=======\n");
              //  bzero(client[descClient].cMapFile, CHUNKSIZE);
        }
        else
        {
            printf("got error at upload in comandana, didn't recieve READY\n");   //Debug line
            //send
            if(send(client[descClient].clientNo, cRecvBuffer, CHUNKSIZE, 0) < 0)
            {
                perror("recv upload funct\n");
            }
        }

    }

    //handle download
    if(strcmp(cCommand, "DOWNLOAD")==0)
    {
        printf("Download cmdana\n");    //Debug line
        bzero(cRecvBuffer, CHUNKSIZE);//empty variable to make sure no exess data is read.
        lseek(client[descClient].iMapFd, 0, SEEK_SET);//set offset of mmf to 0 (beginning of file)

        //write given msg to fsp
        if((write(client[descClient].iMapFd, cBuffer, strlen(cBuffer))) < 0)
        {
            perror("Write to mmf\n");
        }
        printf("cBuffer: %s\n", cBuffer);       //Debug line
        printf("Mapped: %s\n", client[descClient].cMapFile);        //Debug line
        //post semfull
        if(sem_post(client[descClient].semaphoreFull) < 0)
        {
            perror("sem_post semaFull in download\n");
        }
        sleep(1);//Debug for now
        //wait for sem empty .. name is not correct in this case but well use it anyway because else we have to create another sem.
        if(sem_wait(client[descClient].semaphoreFull) < 0)
        {
            perror("sem_wait semaEmpty in commandana download\n");
        }
        printf("descClient = %d\n", descClient);//Debug
        printf("what's in the user map: %s\n", client[descClient].cMapFile);//Debug
        
        //if fsp sends ready .. send ready to client and start download else send error and abort
        if(strcmp(client[descClient].cMapFile, "READY") == 0)
        {
            //send
            printf("Ready for download in cmdana\n");       //Debug line
            if(send(descClient, client[descClient].cMapFile,strlen(client[descClient].cMapFile), 0) < 0)
            {
                perror("recv download funct\n");
            }
            //wait for ready
            if(recv(descClient,cRecvBuffer, CHUNKSIZE, 0 ) < 0)
            {
                perror("recv Upload comandana\n");
            }

            if(strcmp(cRecvBuffer, "READY") == 0)
            {
                printf("ready received from client.\n");
                newdownload(client[descClient].clientNo, client);
            }

        }
        else
        {
            printf("error at download commndana\n");        //Debug line
            //send
            if(send(client[descClient].clientNo, cRecvBuffer, CHUNKSIZE, 0) < 0)
            {
                perror("recv download funct\n");
            }
        }
          
    }
    
    bzero(cBuffer,CHUNKSIZE);//empty variable to make sure no exess data is read.
    bzero(cCommand,CHUNKSIZE);//empty variable to make sure no exess data is read.
    return 0;
}


